# -*- coding: utf8 -*-
import os
import jinja2
import webapp2
import json
import logging

from random import randint
from google.appengine.api import users
from player import *

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])

class PlayerEmailHandler(webapp2.RequestHandler):
    def get_player(self):
        player_email = self.request.get("email")
        player = Player.get_by_email(player_email)
        if player == None:
            self.error(404)
            self.response.write('ERROR 404: Player %s not found' % player_email)
            return None
        return player

class ProcessAuth(webapp2.RequestHandler):
    def get(self):
        email = ''
        nick = ''
        pin = 0000
        words = ''
        user = users.get_current_user()
        if user:
            player = Player().get_by_email(user.email())
            if player is None:
                player = Player(email = user.email(), nickname = user.nickname(), words = [])
                player.put()

            email = player.email
            nick = player.nickname
            pin = player.pin_code
            words = '\n'.join(player.words)

        none = None
        template = JINJA_ENVIRONMENT.get_template('user_cabinet.html')
        self.response.write(template.render({
            "email": email,
            "nick": nick,
            "pin": pin,
            "words": words,
            "logout": users.create_logout_url("/"),
            "login": users.create_login_url("/user_cabinet.html")
            }))

class ProcessGeneratingPin(PlayerEmailHandler):
    def post(self):
        player = self.get_player()
        if player == None:
            return
        player.pin_code = randint(1000, 9999)
        player.put()
        self.redirect("/user_cabinet.html")


class ProcessEditingPlayer(PlayerEmailHandler):
    def post(self):
        player = self.get_player()
        if player == None:
            return
        name = self.request.get("name")
        words_sring = self.request.get("words")
        words = words_sring.split()
        player.nickname = name
        player.words = words
        player.put()
        self.redirect("/user_cabinet.html")


class TmpAddPlayerFromServer(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('tmp_add_player_from_server.html')
        self.response.write(template.render())


class ProcessAddingPlayerFromServer(PlayerEmailHandler):
    def post(self):
        player = self.get_player()
        if player == None:
            return

        pin = int(self.request.get("pin"))
        if player.pin_code != pin:
            self.error(403)
            self.response.write('ERROR 403: You entered wrong pincode')
            return

        dict_json = {
        "name": player.nickname,
        "words": player.words[:49]
        }
        json.dumps(dict_json, sort_keys=True).encode("utf-8")
        self.redirect("/")